/*
 * Copyright 2011 ArcBees Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.arcbees.server.auth;

import java.util.Date;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;

/**
 *
 */
public class AuthenticatorImpl implements Authenticator {
  private final Provider<UserSessionDao> userSessionDaoProvider;
  private final Provider<UserSession> userSessionProvider;
  private final SessionIdGenerator sessionIdGenerator;
  private final CookieUtilities cookieUtilities;
  private final Long cookieTimeOut;

  @Inject
  public AuthenticatorImpl(
      final Provider<UserSessionDao> userSessionDaoProvider,
      final Provider<UserSession> userSessionProvider,
      final SessionIdGenerator sessionIdGenerator,
      final CookieUtilities cookieUtilities,
      @Named("COOKIE_TIMEOUT") final Long cookieTimeOut) {

    this.userSessionDaoProvider = userSessionDaoProvider;
    this.userSessionProvider = userSessionProvider;
    this.sessionIdGenerator = sessionIdGenerator;
    this.cookieUtilities = cookieUtilities;
    this.cookieTimeOut = cookieTimeOut;
  }

  @Override
  public String isAuthenticated(String cookie) {
    UserSessionDao userSessionDao = userSessionDaoProvider.get();

    UserSession userSession = userSessionDao.load(cookie);

    if (userSession != null) {
      return userSession.getUserId();
    } else {
      return null;
    }
  }

  @Override
  public void authenticate(String userId) {
    UserSessionDao userSessionDao = userSessionDaoProvider.get();
    UserSession userSession = userSessionProvider.get();

    userSession.setUserId(userId);
    userSession.setTimeout(getTimeout());
    userSession.setCookie(sessionIdGenerator.getSessionId());

    userSessionDao.store(userSession);

    cookieUtilities.createSessionCookie(userSession);
  }

  @Override
  public void deAuthenticate(String cookie) {
    UserSessionDao userSessionDao = userSessionDaoProvider.get();

    UserSession userSession = userSessionDao.load(cookie);

    if (userSession != null) {
      userSessionDao.delete(userSession);
    }
  }

  /**
   * @return A time stamp with the actual timeout of the cookie.
   */
  private Long getTimeout() {
    Date date = new Date();

    date.setTime(date.getTime() + cookieTimeOut);

    return date.getTime();
  }
}
